package com.leetcode.Hash求解.字符串中的第一个唯一字符;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 参考：https://leetcode-cn.com/problems/first-unique-character-in-a-string/
 * </p>
 *
 * @author: Sunny
 * @date: 2021/3/5
 * @version: v1.0.0
 */
public class Main {

    public static void main(String[] args) {
        System.out.println(searchIndex("loveleetcode"));
    }

    /**
     * @param content
     * @return
     */
    public static int searchIndex(String content) {
        char[] chars = content.toCharArray();
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < chars.length; i++) {
            // 可以优化为
            map.put(chars[i], map.getOrDefault(chars[i], 0) + 1);
//            if (map.containsKey(chars[i])) {
//                map.put(chars[i], map.get(chars[i]) + 1);
//            } else {
//                map.put(chars[i], 1);
//            }
        }
        for (int i = 0; i < chars.length; i++) {
            if (map.get(chars[i]) == 1) {
                return i;
            }
        }
        return -1;
    }

}
